/**
 * 
 */
package com.neusoft.cmsprojects.service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.enterprise.inject.New;
import javax.security.auth.message.callback.PrivateKeyCallback.Request;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.json.JSONException;
import org.apache.struts2.json.JSONUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dreamtags.model.Page;
import com.neusoft.cmsprojects.dao.ArticleManagementDao;
import com.neusoft.cmsprojects.model.CArticlesort;
import com.neusoft.cmsprojects.model.TbArticle;
import com.neusoft.cmsprojects.model.TbUser;
import com.neusoft.cmsprojects.util.FileUtil;
import com.neusoft.cmsprojects.util.ResponseUtil;

/**
 * index: 文章管理相关的业务层接口的实现
 * 
 * @author guanhaimin date:2014年12月20日下午7:21:50
 */
@Service("ArticleManagementService")
@Transactional
public class ArticleManagementServiceImpl implements ArticleManagementService {
	@Resource(name = "ArticleManagementDao")
	private ArticleManagementDao articleManagementDao;

	public ArticleManagementDao getArticleManagementDao() {
		return articleManagementDao;
	}

	public void setArticleManagementDao(
			ArticleManagementDao articleManagementDao) {
		this.articleManagementDao = articleManagementDao;
	}

	@Override
	public void addArticleCategory(CArticlesort carticlesort) throws Exception {
		// TODO Auto-generated method stub
		HttpServletResponse response = ServletActionContext.getResponse();
		TbUser tbUser = (TbUser) ServletActionContext.getRequest().getSession()
				.getAttribute("user");
		String msg = "";
		List<CArticlesort> csZh = this.articleManagementDao
				.selectByCName(carticlesort.getCName());
		List<CArticlesort> csEn = this.articleManagementDao
				.selectByCName(carticlesort.getCNamee());
		Date d = new Date();
		if (csZh == null && csEn == null) {
			carticlesort.setCCreator(tbUser.getCid());
			carticlesort.setCCreatetime(d);
			articleManagementDao.save(carticlesort);
			msg = "文章类别保存成功";
		} else {
			msg = "文章类别名称已存在";
		}
		ResponseUtil.write(response, msg);
	}

	@Override

	public void getArticleCategory(int currentPage, int pageSize,
			String condition) throws JSONException {
		// TODO Auto-generated method stub
		HttpServletRequest request = ServletActionContext.getRequest();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Page page = (Page) request.getSession().getAttribute("Page");
		if (page == null) {
			System.out.println("page为空");
			page = new Page();
		}
		if (condition == null) {
			if (page.getQueryConditions() == null) {
				page.setQueryConditions((HashMap<String, Object>) JSONUtil
						.deserialize("{\"CName\":\"\", \"CNamee\":\"\", \"CTitle\":\"\", \"CTitlee\":\"\", \"CSortid\":\"\", \"startdate\":\"\", \"enddate\":\"\"}"));
				System.out.println(page.getQueryConditions().get("startdate"));
			}
		} else {
			page.setQueryConditions((HashMap<String, Object>) JSONUtil
					.deserialize(condition));
		}
		String hql = "from CArticlesort c where c.CName like '%"
				+ page.getQueryConditions().get("CName") + "%'"
				+ " and c.CNamee like '%"
				+ page.getQueryConditions().get("CNamee") + "%'"
				+ " and c.CCreatetime >='"
				+ page.getQueryConditions().get("startdate") + "'";
		String sql = "select count(*) from CArticlesort c where c.CName like '%"
				+ page.getQueryConditions().get("CName")
				+ "%'"
				+ " and c.CNamee like '%"
				+ page.getQueryConditions().get("CNamee")
				+ "%'"
				+ " and c.CCreatetime >='"
				+ page.getQueryConditions().get("startdate") + "'";
		if (page.getQueryConditions().get("enddate").equals("")) {
			hql = hql + " and c.CCreatetime <='" + sdf.format(new Date()) + "' order by c.CCreatetime desc";
			sql = sql + " and c.CCreatetime <='" + sdf.format(new Date()) + "' order by c.CCreatetime desc";
		} else {
			hql = hql + " and c.CCreatetime <='"
					+ page.getQueryConditions().get("enddate") + " 23:59:59"
					+ "'";
			sql = sql + " and c.CCreatetime <='"
					+ page.getQueryConditions().get("enddate") + " 23:59:59"
					+ "'";
		}
		List<Object> objs = this.articleManagementDao.queryByPage(hql,
				currentPage, pageSize);
		System.out.println(sql);
		int totalcount = this.articleManagementDao.getTotalCountBySql(sql);
		page.setCurrentPage(currentPage);
		page.setTotalRows(totalcount);
		if (totalcount % pageSize == 0) {
			page.setTotalPages(totalcount / pageSize);
		} else {
			page.setTotalPages(totalcount / pageSize + 1);
		}
		page.setPageSize(pageSize);
		request.setAttribute("ArticleCategory", objs);
		request.getSession().setAttribute("Page", page);
	}

	@Override
	public void deleteArticleCategory(int id) throws Exception {
		// TODO Auto-generated method stub
		HttpServletResponse response = ServletActionContext.getResponse();
		String msg = "";
		String hql = "from CArticlesort c where c.CId=" + id;
		CArticlesort carticlesort = (CArticlesort) this.articleManagementDao
				.getById(hql);
		if (carticlesort != null) {
			this.articleManagementDao.delete(carticlesort);
			msg = "DeleteSuccess";
		} else {
			msg = "DataNotExist";
		}
		ResponseUtil.write(response, msg);
	}

	@Override
	public void batchDeleteArticleCategory(String list) throws Exception {
		// TODO Auto-generated method stub
		HttpServletResponse response = ServletActionContext.getResponse();
		String msg = "";
		String hql = "from CArticlesort c where c.CId=";
		List<CArticlesort> carticlesorts = new ArrayList<CArticlesort>();
		if (list != null) {
			String[] idList = list.split(",");
			int flag = 0;
			for (int i = 0; i < idList.length; ++i) {
				String tempHql = hql + idList[i];
				CArticlesort carticlesort = (CArticlesort) this.articleManagementDao
						.getById(tempHql);
				if (carticlesort == null) {
					flag++;
				}
				carticlesorts.add(carticlesort);
			}
			if (flag == 0) {
				for (int i = 0; i < carticlesorts.size(); ++i) {
					this.articleManagementDao.delete(carticlesorts.get(i));
				}
				msg = "BatchDeleteSuccess";
			} else {
				msg = "PartNotExist";
			}
		} else {
			msg = "DataIsNull";
		}
		ResponseUtil.write(response, msg);
	}

	@Override
	public void getArticleCategoryById(int id) {
		// TODO Auto-generated method stub
		HttpServletRequest request = ServletActionContext.getRequest();
		String hql = "from CArticlesort c where c.CId=" + id;
		CArticlesort carticlesort = (CArticlesort) this.articleManagementDao
				.getById(hql);
		if (carticlesort != null) {
			request.setAttribute("ArticleCategory", carticlesort);
		}
	}

	@Override
	public void updateArticleCategory(CArticlesort carticlesort, int id)
			throws Exception {
		// TODO Auto-generated method stub
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest requset = ServletActionContext.getRequest();
		String msg = "";
		String hql = "from CArticlesort c where c.CId=" + id;
		CArticlesort oldCarticlesort = (CArticlesort) this.articleManagementDao
				.getById(hql);
		TbUser user = (TbUser) requset.getSession().getAttribute("user");
		if (carticlesort != null) {
			Date d = new Date();
			List<CArticlesort> csZh = this.articleManagementDao
					.selectByCName(carticlesort.getCName());
			List<CArticlesort> csEn = this.articleManagementDao
					.selectByCName(carticlesort.getCNamee());
			int zhflag = 0;
			int enflag = 0;
			if (csZh != null) {
				for (int i = 0; i < csZh.size(); ++i) {
					if (csZh.get(i).getCId() != carticlesort.getCId()) {
						zhflag++;
					}
				}
			}
			if (csEn != null) {
				for (int i = 0; i < csEn.size(); ++i) {
					if (csEn.get(i).getCId() != carticlesort.getCId()) {
						enflag++;
					}
				}
			}
			if (zhflag == 0 && enflag == 0) {
				oldCarticlesort.setCName(carticlesort.getCName());
				oldCarticlesort.setCNamee(carticlesort.getCNamee());
				oldCarticlesort.setCDescription(carticlesort.getCDescription());
				oldCarticlesort.setCDescriptione(carticlesort
						.getCDescriptione());
				oldCarticlesort.setCModifier(user.getCid());
				oldCarticlesort.setCModifytime(d);
				this.articleManagementDao.update(oldCarticlesort);
				msg = "文章类别保存成功";
			} else {
				if (zhflag > 0 && enflag > 0) {
					msg = "文章类别中英文名称都已存在";
				} else {
					if (zhflag > 0) {
						msg = "文章类别中文名称已存在";
					} else {
						msg = "文章类别英文名称已存在";
					}
				}
			}
		} else {
			msg = "要修改的文章类别不存在";
		}
		ResponseUtil.write(response, msg);
	}

	@Override
	public void saveArticle(TbArticle tbarticle, String content, String contente)
			throws Exception {
		// TODO Auto-generated method stub
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		String msg = "";
		TbUser user = (TbUser) request.getSession().getAttribute("user");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String strdate = sdf.format(new Date());
		if (!tbarticle.getCTitle().trim().equals("")) {
			if (!content.trim().equals("")) {
				if (!tbarticle.getCSortid().trim().equals("")) {
					content = content.replaceAll("src=\"tempfiles/" + strdate
							+ "/", "src=\"/CMSProject/Resources/image/"); // 改变<img/>标签的图片路径
					contente = contente.replaceAll("src=\"tempfiles/" + strdate
							+ "/", "src=\"/CMSProject/Resources/image/"); // 改变<img/>标签的图片路径
					tbarticle.setCContent(content.getBytes());
					tbarticle.setCContente(contente.getBytes());
					tbarticle.setCCreator(user.getCusername());
					tbarticle.setCCreatetime(new Date());
					this.articleManagementDao.save(tbarticle);
					msg = "文章保存成功";
				} else {
					msg = "请选择文章类别";
				}
			} else {
				msg = "中文内容不能为空";
			}
		} else {
			msg = "中文标题不能为空";
		}
		ResponseUtil.write(response, msg);
	}

	@Override
	public void getArticleCategorySort() {
		// TODO Auto-generated method stub
		HttpServletRequest request = ServletActionContext.getRequest();
		String hql = "from CArticlesort c";
		List<Object> objs = this.getArticleManagementDao().queryByHql(hql);
		request.setAttribute("TbArticleSort", objs);
	}

	@Override
	public void getArticle(int currentPage, int pageSize, String condition)
			throws JSONException {
		// TODO Auto-generated method stub
		HttpServletRequest request = ServletActionContext.getRequest();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Page page = (Page) request.getSession().getAttribute("Page");
		if (page == null) {
			page = new Page();
		}
		if (condition == null) {
			if (page.getQueryConditions() == null) {
				page.setQueryConditions((HashMap<String, Object>) JSONUtil
						.deserialize("{\"CName\":\"\", \"CNamee\":\"\", \"CTitle\":\"\", \"CTitlee\":\"\", \"CSortid\":\"\", \"startdate\":\"\", \"enddate\":\"\"}"));
			}
		} else {
			page.setQueryConditions((HashMap<String, Object>) JSONUtil
					.deserialize(condition));
		}
		String hql = "from TbArticle t where t.CTitle like '%"
				+ page.getQueryConditions().get("CTitle") + "%'"
				+ " and t.CTitlee like '%"
				+ page.getQueryConditions().get("CTitlee") + "%'"
				+ " and t.CCreatetime >='"
				+ page.getQueryConditions().get("startdate") + "'";
		String sql = "select count(*) from TbArticle t where t.CTitle like '%"
				+ page.getQueryConditions().get("CTitle") + "%'"
				+ " and t.CTitlee like '%"
				+ page.getQueryConditions().get("CTitle") + "%'"
				+ " and t.CCreatetime >='"
				+ page.getQueryConditions().get("startdate") + "'";
		if (!page.getQueryConditions().get("CSortid").equals("")) {
			hql = hql + " and t.CSortid='"
					+ page.getQueryConditions().get("CSortid") + "'";
			sql = sql + " and t.CSortid='"
					+ page.getQueryConditions().get("CSortid") + "'";
		}
		if (page.getQueryConditions().get("enddate").equals("")) {
			hql = hql + " and t.CCreatetime<='" + sdf.format(new Date()) + "' order by t.CCreatetime desc";
			sql = sql + " and t.CCreatetime<='" + sdf.format(new Date()) + "'";
		} else {
			hql = hql + " and t.CCreatetime<='"
					+ page.getQueryConditions().get("enddate") + " 23:59:59"
					+ "' order by t.CCreatetime desc";
			sql = sql + " and t.CCreatetime<='"
					+ page.getQueryConditions().get("enddate") + " 23:59:59"
					+ "'";
		}
		List<Object> objs = this.articleManagementDao.queryByPage(hql,
				currentPage, pageSize);
		int totalcount = this.articleManagementDao.getTotalCountBySql(sql);
		page.setCurrentPage(currentPage);
		page.setTotalRows(totalcount);
		if (totalcount % pageSize == 0) {
			page.setTotalPages(totalcount / pageSize);
		} else {
			page.setTotalPages(totalcount / pageSize + 1);
		}
		page.setPageSize(pageSize);
		request.setAttribute("Article", objs);
		request.getSession().setAttribute("Page", page);
	}

	@Override
	public void getArticleById(int id) {
		// TODO Auto-generated method stub
		HttpServletRequest request = ServletActionContext.getRequest();
		String hql = "from TbArticle t where t.CId=" + id;
		TbArticle tbarticle = (TbArticle) this.articleManagementDao
				.getById(hql);
		if (tbarticle != null) {
			request.setAttribute("ZhData", new String(tbarticle.getCContent()));
			request.setAttribute("EnData", new String(tbarticle.getCContente()));
			request.setAttribute("Article", tbarticle);
		}
	}

	@Override
	public void updateArticle(TbArticle tbarticle, String content,
			String contente) throws Exception {
		// TODO Auto-generated method stub
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest requset = ServletActionContext.getRequest();
		String msg = "";
		String hql = "from TbArticle t where t.CId=" + tbarticle.getCId();
		TbArticle oldTbArticle = (TbArticle) this.articleManagementDao
				.getById(hql);
		TbUser user = (TbUser) requset.getSession().getAttribute("user");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String strdate = sdf.format(new Date());
		if (oldTbArticle != null) {
			if (!tbarticle.getCTitle().trim().equals("")) {
				if (!content.trim().equals("")) {
					if (!tbarticle.getCSortid().trim().equals("")) {
						content = content.replaceAll("src=\"tempfiles/"
								+ strdate + "/",
								"src=\"/CMSProject/Resources/image/"); // 改变<img/>标签的图片路径
						contente = contente.replaceAll("src=\"tempfiles/"
								+ strdate + "/",
								"src=\"/CMSProject/Resources/image/"); // 改变<img/>标签的图片路径
						oldTbArticle.setCTitle(tbarticle.getCTitle());
						oldTbArticle.setCTitlee(tbarticle.getCTitlee());
						oldTbArticle.setCContent(content.getBytes());
						oldTbArticle.setCContente(contente.getBytes());
						oldTbArticle.setCModifier(user.getCusername());
						oldTbArticle.setCModifytime(new Date());
						this.articleManagementDao.update(oldTbArticle);
						msg = "文章修改成功";
					} else {
						msg = "请选择文章类别";
					}
				} else {
					msg = "中文内容不能为空";
				}
			} else {
				msg = "中文标题不能为空";
			}
		} else {
			msg = "要修改的数据已不存在";
		}
		ResponseUtil.write(response, msg);
	}

	@Override
	public void saveFile(String content, String opt, int id) throws IOException {
		// TODO Auto-generated method stub
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String strdate = sdf.format(new Date());
		if (opt.trim().equals("NEW")) {
			content = content.replaceAll("src=\"tempfiles/" + strdate + "/",
					"src=\"/CMSProject/Resources/image/"); // 改变<img/>标签的图片路径
			FileUtil.saveImageFromText("tempfiles\\" + strdate + "/",
					"\\Resources\\image\\", content,
					"src=\"/CMSProject/Resources/image/(.*?)\""); // 将临时文件夹里面的图片移到指定的资源文件夹中
		} else {
			content = content.replaceAll("src=\"tempfiles/" + strdate + "/",
					"src=\"/CMSProject/Resources/image/"); // 改变<img/>标签的图片路径
			if (opt.trim().equals("EDITzh")) {
				String hql = "from TbArticle t where t.CId=" + id;
				TbArticle tempArticle = (TbArticle) this.articleManagementDao
						.getById(hql);
				if (tempArticle != null) {
					FileUtil.saveImageFromText("Resources\\image\\",
							"tempfiles\\" + strdate + "\\", new String(
									tempArticle.getCContent()),
							"src=\"/CMSProject/Resources/image/(.*?)\"");// 将文章中的原图片转存到临时文件夹
					FileUtil.saveImageFromText("tempfiles\\" + strdate + "\\",
							"Resources\\image\\", content,
							"src=\"/CMSProject/Resources/image/(.*?)\""); // 将文章中原图片从临时文件夹中取回
				}
			} else {
				if (opt.trim().equals("EDITen")) {
					String hql = "from TbArticle t where t.CId=" + id;
					TbArticle tempArticle = (TbArticle) this.articleManagementDao
							.getById(hql);
					FileUtil.saveImageFromText("Resources\\image\\",
							"tempfiles\\" + strdate + "\\", new String(
									tempArticle.getCContente()),
							"src=\"/CMSProject/Resources/image/(.*?)\"");// 将文章中的原图片转存到临时文件夹
					FileUtil.saveImageFromText("tempfiles\\" + strdate + "\\",
							"Resources\\image\\", content,
							"src=\"/CMSProject/Resources/image/(.*?)\""); // 将文章中原图片从临时文件夹中取回
				}
			}
		}
	}

	@Override
	public void deleteArticle(int id) throws Exception {
		// TODO Auto-generated method stub
		HttpServletResponse response = ServletActionContext.getResponse();
		String msg = "";
		String hql = "from TbArticle t where t.CId=" + id;
		TbArticle tempArticle = (TbArticle) this.articleManagementDao
				.getById(hql);
		if (tempArticle != null) {
			FileUtil.deleteImageFromText("Resources\\image\\", new String(
					tempArticle.getCContent()),
					"src=\"/CMSProject/Resources/image/(.*?)\" title=\"");
			FileUtil.deleteImageFromText("Resources\\image\\", new String(
					tempArticle.getCContente()),
					"src=\"/CMSProject/Resources/image/(.*?)\" title=\"");
			this.articleManagementDao.delete(tempArticle);
			msg = "文章删除成功";
		} else {
			msg = "要删除的文章已不存在";
		}
		ResponseUtil.write(response, msg);
	}

	@Override
	public void batchDeleteArticle(String list) throws Exception {
		// TODO Auto-generated method stub
		HttpServletResponse response = ServletActionContext.getResponse();
		String msg = "";
		String hql = "from TbArticle t where t.CId=";
		List<TbArticle> tbArticles = new ArrayList<TbArticle>();
		if (list != null) {
			String[] idList = list.split(",");
			int flag = 0;
			for (int i = 0; i < idList.length; ++i) {
				String tempHql = hql + idList[i];
				TbArticle tbArticle = (TbArticle) this.articleManagementDao
						.getById(tempHql);
				if (tbArticle == null) {
					flag++;
				}
				tbArticles.add(tbArticle);
			}
			if (flag == 0) {
				for (int i = 0; i < tbArticles.size(); ++i) {
					FileUtil.deleteImageFromText("Resources\\image\\",
							new String(tbArticles.get(i).getCContent()),
							"src=\"/CMSProject/Resources/image/(.*?)\" title=\"");
					FileUtil.deleteImageFromText("Resources\\image\\",
							new String(tbArticles.get(i).getCContente()),
							"src=\"/CMSProject/Resources/image/(.*?)\" title=\"");
					this.articleManagementDao.delete(tbArticles.get(i));
				}
				msg = "批量删除成功";
			} else {
				msg = "存在不存在记录";
			}
		} else {
			msg = "没有选中记录";
		}
		ResponseUtil.write(response, msg);
	}
}
